package com.game.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.game.common.Result;
import com.game.sys.entity.Game;
import com.game.sys.service.IGameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;



import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author limeng
 * @since 2023-03-23
 */
@RestController
@RequestMapping("/game")
public class GameController {
    @Autowired
    private IGameService gameService;

    @PostMapping
    public Result<?> addGame(@RequestBody Game game){
        gameService.save(game);
        return Result.success("游戏添加成功");
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteGameById(@PathVariable Integer id){
        gameService.removeById(id);
        return Result.success("游戏删除成功");
    }

    @PutMapping
    public Result<?> updateGameById(@RequestBody Game game){
        gameService.updateById(game);
        return Result.success("游戏修改成功");
    }

    @GetMapping("/{id}")
    public Result<Game> getGameById(@PathVariable Integer id){
        Game byId = gameService.getById(id);
        return Result.success(byId);
    }

    @GetMapping("/one")
    public Result<Game> getGameByName(
            @RequestParam(value = "name",required = false) String name){
        LambdaQueryWrapper<Game> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name), Game::getName,name);

        Game one = gameService.getOne(wrapper);
        return Result.success(one);
    }

    @GetMapping("/all")
    public Result<Map<String,Object>> getAllGame(
            @RequestParam(value = "name",required = false) String name,
            @RequestParam(value = "type",required = false) String type,
            @RequestParam(value = "client",required = false) String client,
            @RequestParam(value = "company",required = false) String company,
            @RequestParam("pageNo") Long pageNo,
            @RequestParam("pageSize") Long pageSize){
        LambdaQueryWrapper<Game> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name), Game::getName,name);
        wrapper.like(StringUtils.hasLength(type),Game::getType,type);
        wrapper.like(StringUtils.hasLength(client),Game::getClient,client);
        wrapper.like(StringUtils.hasLength(company),Game::getCompany,company);

        Page<Game> page = new Page<>(pageNo, pageSize);
        gameService.page(page,wrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("rows",page.getRecords());
        return Result.success(map);
    }
}
